package hr.koshnica.android.database;

import hr.koshnica.android.database.KoshnicaContract.Events;
import hr.koshnica.android.database.KoshnicaContract.Locations;
import hr.koshnica.android.database.KoshnicaContract.SearchColumns;
import hr.koshnica.android.database.KoshnicaDatabase.Tables;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;

public class KoshnicaProvider extends ContentProvider{

	 private static final UriMatcher sUriMatcher = buildUriMatcher();
	 
	 private static final int LOCATIONS = 100;
	 
	 private static final int LOCATIONS_ID = 101;
	 
	 private static final int EVENTS = 200;
	 
	 private static final int EVENTS_ID = 201;
	 
	 private static final int SEARCH = 400;
	 
	 private static final int SEARCH_ID = 401;
	 
	 private static final int SEARCH_SUGGEST = 800;
	 
	 private static UriMatcher buildUriMatcher(){

         final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
         final String authority = KoshnicaContract.CONTENT_AUTHORITY;
        
         //Locations
         matcher.addURI(authority, KoshnicaContract.PATH_LOCATIONS, LOCATIONS);
         matcher.addURI(authority, KoshnicaContract.PATH_LOCATIONS + "/*", LOCATIONS_ID);
         
         //Events
         matcher.addURI(authority, KoshnicaContract.PATH_EVENTS, EVENTS);
         matcher.addURI(authority, KoshnicaContract.PATH_EVENTS + "/*", EVENTS_ID);
         
        // Search
         matcher.addURI(authority, KoshnicaContract.PATH_SEARCH, SEARCH);
         matcher.addURI(authority, KoshnicaContract.PATH_SEARCH + "/*", SEARCH_ID);
            
         // Suggestions
         matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST);
         matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST);
         
         return matcher;    
     }
	
	 private KoshnicaDatabase mOpenHelper;
	 
	 @Override
	 public boolean onCreate() {   	        
		 mOpenHelper = new KoshnicaDatabase(getContext());
	     return true;
	 }
	 
	 @Override
	 public String getType(Uri uri) {
		 	        
		 final int match = sUriMatcher.match(uri);	        
		 switch (match) {	            
		 	case LOCATIONS:	                
		 		return Locations.CONTENT_TYPE;            
		 	case LOCATIONS_ID:	                
		 		return Locations.CONTENT_ITEM_TYPE;
		 	case EVENTS:	                
		 		return Events.CONTENT_TYPE;            
		 	case EVENTS_ID:	                
		 		return Events.CONTENT_ITEM_TYPE;	
		 	case SEARCH_SUGGEST:               
		 		return SearchManager.SUGGEST_MIME_TYPE;	            
		 	default:	                
		 		throw new UnsupportedOperationException("Unknown uri: " + uri);
	        }
	 }
	 
	 @Override
	    
	 public Uri insert(Uri uri, ContentValues values) {	   	 

		 final int match = sUriMatcher.match(uri);
		 mOpenHelper.open();
		 
		 switch (match) {
	    	case LOCATIONS: {  	        	    		            
	    		mOpenHelper.insertInput(Tables.LOCATIONS, values);          	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	    		mOpenHelper.close();
	           
	    		return Locations.buildLocationUri(values.getAsString(BaseColumns._ID));	            
	    	}
	    	case EVENTS: {  	            			            
	    		mOpenHelper.insertInput(Tables.EVENTS, values);          	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	    		mOpenHelper.close();
	           
	    		return Events.buildEventUri(values.getAsString(BaseColumns._ID));	            
	    	}  
	    	default: {	        
	    		throw new UnsupportedOperationException("Unknown uri: " + uri);	            
	    	}	        	    
		 }	    	
	 }

	 @Override
	    
	 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,	 
			 String sortOrder) {
		 
		 mOpenHelper.open();	     
     
		 final int match = sUriMatcher.match(uri);	     
		 
		 switch (match) {	     		
		 	case SEARCH: {	                
		 		if (selectionArgs == null) {	            
		 			throw new IllegalArgumentException(	                
		 					"selectionArgs must be provided for the Uri: " + uri);	                
		 		}	            		 	 
		 		Cursor query = getSearch(selectionArgs[0]);
		 		mOpenHelper.close();
		 		return query;  
		 	}	        
		 	case SEARCH_SUGGEST: {	        
		 		if (selectionArgs == null) {            
		 			throw new IllegalArgumentException(	                
		 					"selectionArgs must be provided for the Uri: " + uri);	            
		 		}
		 		Cursor query = getSuggestions(selectionArgs[0]);
		 		mOpenHelper.close();
		 		return query;            
		 	}        
		 	case LOCATIONS: {  	   
		 		Cursor query = mOpenHelper.queryInputs(Tables.LOCATIONS, projection, selection, selectionArgs, 
	    					null, null, sortOrder); 			       	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	    		mOpenHelper.close();
	           
	    		return query;	    
	    	}
	    	case EVENTS: {  	            			                     	                
	    		Cursor query = mOpenHelper.queryInputs(Tables.EVENTS, projection, selection, selectionArgs, 
    					null, null, sortOrder); 			       	                
    		getContext().getContentResolver().notifyChange(uri, null);	            
    		mOpenHelper.close();
           
    		return query;           
	    	}  
	    	case LOCATIONS_ID: {  	
	    		Cursor query;
	    			
	    		final String[] locationId = {Locations.getLocationId(uri)};  				
	    		query = mOpenHelper.fetchInput(Tables.LOCATIONS, projection, Long.parseLong(locationId[0])); 	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	           
	    		return query;	    
	    	}
	    	case EVENTS_ID: {  	            			                     	                
	    		Cursor query;
    			
	    		final String[] eventId = {Events.getEventId(uri)};  				
	    		query = mOpenHelper.fetchInput(Tables.EVENTS, projection, Long.parseLong(eventId[0])); 	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	           
	    		return query;	            
	    	}  
	    	default: {	        
	    		throw new UnsupportedOperationException("Unknown uri: " + uri);	            
	    	}      
		 }    
	 }
	    
	 private Cursor getSearch(String query){
		 String[] columns = new String[] {	     				 
				 BaseColumns._ID,	            
				 SearchColumns.TITLE,	            
				 SearchColumns.OVERVIEW,
				 //SearchColumns.DATA_ID,
				 SearchColumns.EXTRA_DATA	
				 /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
	                          (only if you want to refresh shortcuts) */
	            };	        
		 return mOpenHelper.getSearchMatches(query, columns);	     
	 }
	 
	 private Cursor getSuggestions(String query) {	 
		 query = query.toLowerCase();	     
		 String[] columns = new String[] {
				 BaseColumns._ID ,	            
				 SearchColumns.TITLE + " as "
			                + SearchManager.SUGGEST_COLUMN_TEXT_1 ,	            
				 SearchColumns.OVERVIEW + " as "
			                + SearchManager.SUGGEST_COLUMN_TEXT_2,	
			     //SearchColumns.DATA_ID,
				 SearchColumns.EXTRA_DATA
			                
				 /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
	                          (only if you want to refresh shortcuts) */
	            };	        
		 return mOpenHelper.getSearchMatches(query, columns);	     
	 }

	 
	 @Override	    
	 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {	        
		 final int match = sUriMatcher.match(uri);
		 
		 int result = -1;
		 mOpenHelper.open();
		 
		 switch (match) {
	    	case LOCATIONS_ID: {  	        	    		            	    	    			           
	    		if (!TextUtils.isEmpty(selection)) 
    				result = mOpenHelper.updateInput(Tables.LOCATIONS, selection, selectionArgs, values); 
    			else {
    				final String[] locationId = {Locations.getLocationId(uri)};
    				result = mOpenHelper.updateInput(Tables.LOCATIONS, BaseColumns._ID + "=?", locationId, values);
    			}          	                
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	    		mOpenHelper.close();
	           
	    		return result;	    
	    	}
	    	case EVENTS_ID: {  	            			                     	                
	    		if (!TextUtils.isEmpty(selection)) 
    				result = mOpenHelper.updateInput(Tables.EVENTS, selection, selectionArgs, values); 
    			else {
    				final String[] eventId = {Events.getEventId(uri)};
    				result = mOpenHelper.updateInput(Tables.EVENTS, BaseColumns._ID + "=?", eventId, values);
    			}                 
	    		getContext().getContentResolver().notifyChange(uri, null);	            
	    		mOpenHelper.close();
	           
	    		return result;	            
	    	}  
	    	default: {	        
	    		throw new UnsupportedOperationException("Unknown uri: " + uri);	            
	    	}	        	    
		 }	
	       
	    }

	    /** {@inheritDoc} */
	    @Override
	    public int delete(Uri uri, String selection, String[] selectionArgs) {
	    	final int match = sUriMatcher.match(uri);
	    	
	    	int result = -1;
	    	mOpenHelper.open();
			 
	    	switch (match) {
	    		case LOCATIONS_ID: {  	        	    		  
	    			if (!TextUtils.isEmpty(selection)) 
	    				result = mOpenHelper.deleteInput(Tables.LOCATIONS, selection, selectionArgs); 
	    			else {
	    				final String[] locationId = {Locations.getLocationId(uri)};
	    				result = mOpenHelper.deleteInput(Tables.LOCATIONS, BaseColumns._ID + "=?", locationId);
	    			}          	                
		    		getContext().getContentResolver().notifyChange(uri, null);	            
		    		mOpenHelper.close();
		           
		    		return result;	            
		    	}
		    	case EVENTS_ID: {  	   
		    		if (!TextUtils.isEmpty(selection)) 
	    				result = mOpenHelper.deleteInput(Tables.EVENTS, selection, selectionArgs); 
	    			else {
	    				final String[] eventId = {Events.getEventId(uri)};
	    				result = mOpenHelper.deleteInput(Tables.EVENTS, BaseColumns._ID + "=?", eventId);
	    			} 		    		        	                
		    		getContext().getContentResolver().notifyChange(uri, null);	            
		    		mOpenHelper.close();
		           
		    		return result;	            
		    	}  
		    	default: {	        
		    		throw new UnsupportedOperationException("Unknown uri: " + uri);	            
		    	}	        	     
	    	}	
		       
		    
	    }
	    
}
	 

